package com.yuzai.reading.controllers;

import cn.hutool.core.util.ObjectUtil;
import com.yuzai.reading.commons.result.Result;
import com.yuzai.reading.dtos.ActiveDTO;
import com.yuzai.reading.dtos.UserDTO;
import com.yuzai.reading.entitys.UserEntity;
import com.yuzai.reading.properties.JwtProperties;
import com.yuzai.reading.services.UserService;
import com.yuzai.reading.utils.JwtUtil;
import com.yuzai.reading.vos.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        //数据库查询
        boolean login_flag = userService.queryUser(userDTO);
        if (login_flag) {
            //生成token
            String token = JwtUtil.createToken(userDTO.getUsername(), jwtProperties.getSecretKey(), jwtProperties.getLongTime());
            //将token插入数据库
            userService.updateUserToken(userDTO, token);
            Result<String> success = Result.success(token);
            return success;
        }
        Result<String> error = Result.error("账号或者密码错误！");
        return error;
    }


    @PostMapping
    public Result register(@RequestBody UserDTO userDTO) {

        UserEntity userEntity = userService.register(userDTO);
        if (ObjectUtil.isNull(userEntity)) {
            Result<String> error = Result.error("账号已存在！");
            return error;
        }
        //生成token
        String token = JwtUtil.createToken(userDTO.getUsername(), jwtProperties.getSecretKey(), jwtProperties.getLongTime());
        //将token插入数据库
        userService.updateUserToken(userDTO, token);
        UserVO userVO = new UserVO();
        userVO.setToken(token)
                .setUsername(userDTO.getUsername());
        Result<UserVO> success = Result.success(userVO);
        return success;
    }


    /**
     * 开通账号权限，需要调用卡密系统
     *
     * @param activeDTO
     * @return
     */
    @PostMapping
    public Result active(@RequestBody ActiveDTO activeDTO) {
        boolean checkSecret = userService.checkSecret(activeDTO.getSecret());
        if (checkSecret){
            //

        }
        Result<String> success = Result.success("");
        return null;
    }


}
